#!/bin/bash
# 快速启动脚本（Linux/Mac）- 启动所有服务

echo "========================================"
echo "快速启动所有服务"
echo "========================================"
echo ""

# 获取脚本所在目录
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"

# 检查Redis
echo "检查Redis连接..."
python3 -c "import redis; r = redis.Redis(host='127.0.0.1', port=6379, db=0); r.ping(); print('Redis连接正常')" 2>/dev/null
if [ $? -ne 0 ]; then
    echo "警告: Redis未运行，Celery将无法启动"
    echo "请先启动Redis: redis-server"
    echo ""
fi

cd "$PROJECT_DIR/backend"
source venv/bin/activate

# 启动Django服务
echo "启动Django后端服务..."
python manage.py runserver > /tmp/django.log 2>&1 &
DJANGO_PID=$!
sleep 3

# 启动Celery Worker
echo "启动Celery Worker..."
celery -A travel_plan worker --loglevel=info > /tmp/celery_worker.log 2>&1 &
WORKER_PID=$!
sleep 2

# 启动Celery Beat
echo "启动Celery Beat..."
celery -A travel_plan beat --loglevel=info > /tmp/celery_beat.log 2>&1 &
BEAT_PID=$!
sleep 2

# 启动前端服务
cd "$PROJECT_DIR/frontend"
if [ -f "package.json" ]; then
    echo "启动前端服务..."
    npm run serve > /tmp/vue.log 2>&1 &
    VUE_PID=$!
else
    echo "警告: 前端目录不存在或package.json未找到"
    VUE_PID=""
fi

echo ""
echo "========================================"
echo "所有服务已启动！"
echo "========================================"
echo ""
echo "服务进程ID："
echo "- Django Server: $DJANGO_PID"
echo "- Celery Worker: $WORKER_PID"
echo "- Celery Beat: $BEAT_PID"
if [ -n "$VUE_PID" ]; then
    echo "- Vue Frontend: $VUE_PID"
fi
echo ""
echo "访问地址："
echo "- 前端: http://localhost:8080"
echo "- 后端API: http://localhost:8000/api/"
echo ""
echo "日志文件："
echo "- Django: /tmp/django.log"
echo "- Celery Worker: /tmp/celery_worker.log"
echo "- Celery Beat: /tmp/celery_beat.log"
if [ -n "$VUE_PID" ]; then
    echo "- Vue: /tmp/vue.log"
fi
echo ""
echo "停止服务: kill $DJANGO_PID $WORKER_PID $BEAT_PID $VUE_PID"
echo ""

# 等待用户中断
trap "kill $DJANGO_PID $WORKER_PID $BEAT_PID $VUE_PID 2>/dev/null; exit" INT TERM
wait

